package com.iflytek.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author yfliu9
 * @version 1.0
 * @description: TODO
 * @date 2021/8/25 19:56
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/invoke")
    public String invoke() {
/*        System.out.println("user demo");
        //调用订单服务 服务地址：http://localhost:9999/orders/demo
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject("http://localhost:9999/orders/demo", String.class);
        log.info("请求order服务，获取结果：{}", result);*/

        //使用ribbon + RestTemplate实现负载均衡
        //DiscoveryClient LoadBalanceClient
/*        List<ServiceInstance> instanceList = discoveryClient.getInstances("orders");
        for (ServiceInstance serviceInstance : instanceList) {
            log.info("服务主机：{}，服务端口：{}, 服务地址：{}", serviceInstance.getHost(), serviceInstance.getPort(), serviceInstance.getUri());
        }
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(instanceList.get(0).getUri() + "/orders//demo", String.class);
        log.info("从订单服务进行请求获取结果：{}", result);*/

/*        //使用LoadBalancerClient 实现负载均衡，默认策略：轮训策略
        ServiceInstance serviceInstance = loadBalancerClient.choose("orders");
        log.info("服务主机：{}，服务端口：{}, 服务地址：{}", serviceInstance.getHost(), serviceInstance.getPort(), serviceInstance.getUri());
        String result = restTemplate.getForObject(serviceInstance.getUri() + "/orders//demo", String.class);
        log.info("从订单服务进行请求获取结果：{}", result);*/

        //使用@LoadBalance 注解
        String result = restTemplate.getForObject( "http://orders/orders/demo", String.class);
        log.info("从订单服务进行请求获取结果：{}", result);
        return "ok";
    }
}
